package mutt.server;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.*;

/**
 * The <code>CalculatorEngine</code> class initializes and wraps a
 * <code>ScriptEngine</code>.
 *
 * @author Sander Medri
 * @author Margus Martsepp
 */
public class CalculatorEngine {
    public static final String DEFAULT_ENGINE = "jruby";

    private ScriptEngine engine;

    public CalculatorEngine(String engineName) {
        engine = new ScriptEngineManager().getEngineByName(engineName);
    }

    public CalculatorEngine() {
        this(DEFAULT_ENGINE);
    }

    /**
     * Evaluates the specified expression and returns the result.
     * @param expression the expression to evaluate
     * @return the result of the evaluation
     * @throws ScriptException if there is a problem with the expression
     * @throws NullPointerException if there was a problem starting the engine
     */
    public Object eval(String expression) throws ScriptException, NullPointerException {
        if (engine==null) {
            throw new NullPointerException("No engine initiated");
        }

        return engine.eval(expression);
    }

    /**
     * Evaluates the specified file.
     * @param fileStream InputStream for the file to evaluate
     * @throws java.io.IOException if there is a problem reading the stream
     * @throws javax.script.ScriptException if there is a problem with the script
     */
    public void evalFile(InputStream fileStream) throws IOException, ScriptException {
            String line, file = "";
            BufferedReader reader = new BufferedReader(new InputStreamReader(fileStream));

            while((line = reader.readLine()) != null) {
                file += line + '\n';
            }

            this.eval(file);
    }
}
